package com.imooc.mail.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.imooc.mail.dao.ProductExtMapper;
import com.imooc.mail.dao.ProductMapper;
import com.imooc.mail.pojo.Product;
import com.imooc.mail.service.ICategoryService;
import com.imooc.mail.service.IProductService;
import com.imooc.mail.vo.ProductDetailVo;
import com.imooc.mail.vo.ProductVo;
import com.imooc.mail.vo.ResponseVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static com.imooc.mail.enums.ProductStatusEnum.*;
import static com.imooc.mail.enums.ResponseEnum.PRODUCT_OFF_SALE_OR_DELETE;

/**
 * @Author wjc
 * Date on 2020/6/6 23:47
 */
@Service
public class ProductServiceImpl implements IProductService {

    @Autowired
    private ICategoryService categoryService;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private ProductExtMapper productExtMapper;

    @Override
    public ResponseVo<PageInfo<ProductVo>> list(Integer categoryId, Integer pageNum, Integer pageSize) {
        HashSet<Integer> categoryIdSet = new HashSet<>();
        if (Objects.nonNull(categoryId)) {
            categoryService.findSubCategoryId(categoryId, categoryIdSet);
            categoryIdSet.add(categoryId);
        }

        PageHelper.startPage(pageNum, pageSize);

        List<ProductVo> productVos = productExtMapper.selectByCategoryIdSet(categoryIdSet).stream().map(e -> {
            ProductVo productVo = new ProductVo();
            BeanUtils.copyProperties(e, productVo);
            return productVo;
        }).collect(Collectors.toList());

        PageInfo<ProductVo> pageInfo = new PageInfo<>(productVos);
        return ResponseVo.success(pageInfo);
//        return ResponseVo.success(productVos);
    }

    @Override
    public ResponseVo<ProductDetailVo> detail(Integer productId) {
        Product product = productMapper.selectByPrimaryKey(productId);

        //只对确定性条件判断
        if (product.getStatus().equals(OFF_SALE.getCode())
                || product.getStatus().equals(DELETE.getCode())) {
            return ResponseVo.error(PRODUCT_OFF_SALE_OR_DELETE);
        }

        ProductDetailVo productDetailVo = new ProductDetailVo();
        BeanUtils.copyProperties(product, productDetailVo);
        //敏感数据处理
        productDetailVo.setStock(product.getStock() > 100 ? 100 : product.getStock());
        return ResponseVo.success(productDetailVo);
    }


}
